import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  ScrollView,
  Keyboard,
  DeviceEventEmitter,
} from 'react-native';
import {connect} from 'react-redux';
import I18n from 'react-native-i18n';
import BaseComponent from '../base/BaseComponent';
import {LinearButton, LinearBoardButton} from '../../components/Button';
import {updateUser, logoffAccount} from '../../api/user';
import StorageManager, {USER_INFO} from '../../storage';
import {updateUserInfo, userLogout} from '../../redux/action';
import * as ImagePicker from 'react-native-image-picker';
import {NormalHeader} from '../../components/NavigationHeader';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#160231',
  },
  infoForm: {
    textAlign: 'center',
    flexDirection: 'column',
    paddingLeft: 40,
    paddingRight: 40,
  },
  username: {
    backgroundColor: '#fff',
    height: 44,
    marginBottom: 20,
    borderRadius: 22,
    paddingLeft: 22,
    paddingRight: 22,
    marginTop: 20,
  },
  bio: {
    backgroundColor: '#fff',
    marginBottom: 20,
    borderRadius: 22,
    height: 150,
    padding: 22,
    paddingTop: 22,
  },
});

class EditUserInfo extends BaseComponent {
  constructor(props) {
    super(props);

    console.log(props);

    this.state = {
      nickName: props.userInfo.nickName,
      identify: props.userInfo.identify,
      introduction: props.userInfo.introduction,
      avatar: props.userInfo.image,
    };
  }

  componentDidMount() {
    super.componentDidMount();
  }

  alertLogoff = () => {
    if (this.props.currentRoom) {
      this._showAlert({content: 'please quit room first.'});
      return;
    }

    this._showAlert({
      content: 'Are you sure to logoff your account ,you info will be empty!',
      okTitle: 'Sure',
      alertOkPress: () => {
        logoffAccount({userToken: this.props.userInfo.token})
          .then(async (res) => {
            //退出
            DeviceEventEmitter.emit('userQuitRoom', {
              needQuitRoomScreen: false,
            });

            await this.props.userLogout();
            this.props.navigation.navigate('Login');
          })
          .catch((err) => {
            this._showAlert({content: err});
          });
      },
      cancelTitle: 'Cancel',
    });
  };

  doNext = () => {
    console.log(this.state);
    if (
      ['nickName', 'identify', 'introduction'].some(
        (item) => this.state[item] == '',
      )
    ) {
      this._showAlert({
        content: 'Please input all user information.',
      });

      return;
    }

    this._showLoading();

    //判断是否更新了头像
    var avatar = [{uri: this.state.avatar, name: 'icon'}];
    if (this.state.avatar == this.props.userInfo.image) {
      avatar = null;
    }

    updateUser(
      {
        ...this.state,
        userToken: this.props.userInfo.token,
      },
      avatar,
    )
      .then(async (res) => {
        await this.props.updateUserInfo(res.data);
        this._hideLoading();
        if (this.props.navigation.state.params) {
          this.props.navigation.state.params.refresh(
            this.state.nickName,
            this.state.introduction,
          );
        }
        this.props.navigation.goBack();
      })
      .catch((err) => {
        this._hideLoading();
        this._showAlert({content: err.msg || err});
      });
  };

  renderComponent = () => {
    return (
      <View style={styles.container}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Edit Info"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView keyboardDismissMode style={styles.infoForm}>
          <Text
            style={{
              marginTop: 60,
              color: 'white',
              fontSize: 22,
              fontWeight: 'bold',
              alignSelf: 'center',
            }}>
            {I18n.t('login.improve')}
          </Text>
          <TouchableOpacity
            style={{
              marginTop: 20,
              borderRadius: 60,
              borderColor: '#fff',
              borderWidth: 2,
              padding: 20,
              justifyContent: 'center',
              alignItems: 'center',
              width: 120,
              height: 120,
              alignSelf: 'center',
            }}
            onPress={() => {
              ImagePicker.launchImageLibrary(
                {
                  mediaType: 'photo',
                  includeBase64: false,
                  maxHeight: 200,
                  maxWidth: 200,
                },
                (res) => {
                  console.log(res);
                  if (!res.errorCode && res.uri) {
                    this.setState({
                      avatar: res.uri,
                    });
                  }
                },
              );
            }}>
            <Image
              style={{
                // backgroundColor: 'red',
                width: 100,
                height: 100,
                borderRadius: 50,
              }}
              source={
                this.state.avatar
                  ? {uri: this.state.avatar}
                  : require('../../assets/login/default_user_icon.png')
              }
            />
          </TouchableOpacity>

          <TextInput
            style={styles.username}
            placeholder={I18n.t('login.info_name')}
            placeholderTextColor="#a1a1a1"
            value={this.state.nickName}
            onChangeText={(text) => {
              this.setState({
                nickName: text,
              });
            }}></TextInput>
          {/* <TextInput
            style={[styles.username, {backgroundColor: '#B6B6B6'}]}
            placeholder={I18n.t('login.info_id')}
            placeholderTextColor="#a1a1a1"
            keyboardType="email-address"
            value={this.state.identify}
            editable={false}
            onChangeText={(text) => {
              this.setState({
                identify: text,
              });
            }}></TextInput> */}
          <TextInput
            style={styles.bio}
            placeholder={I18n.t('login.info_bio')}
            placeholderTextColor="#a1a1a1"
            multiline
            value={this.state.introduction}
            onChangeText={(text) => {
              this.setState({
                introduction: text,
              });
            }}></TextInput>
          <LinearButton text="Done" onPress={this.doNext} />
          <LinearBoardButton
            buttonStyle={{height: 44}}
            text="Logoff Account"
            onPress={this.alertLogoff}
          />
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  widgetLayout: state.Layout.widgetLayout,
  currentRoom: state.User.currentRoom,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  userLogout: (item) => dispatch(userLogout()),
});

export default connect(mapStateToProps, mapDispatchToProps)(EditUserInfo);
